package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.properties.ReportExcelProperties;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Autowired
    private ReportExcelProperties reportExcelProperties;

    /**
     * 营业额统计
     * 
 * @param begin
 * @param end
     * @return 
     * @author heiheiheng
     * @create 2025/8/13
     **/
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //准备日期列表数据
        List<LocalDate> localDateTimes = getDateList(begin, end);
        List<Double> trunoverList = new ArrayList<>();
        localDateTimes.forEach(data ->{
            //准备营业额列表数据
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", LocalDateTime.of(data, LocalTime.MIN));
            map.put("end", LocalDateTime.of(data, LocalTime.MAX));
            Double turnover = ordersMapper.sumByMap(map);
            turnover = turnover == null ? 0 : turnover;
            trunoverList.add(turnover);
        });

        //构造并返回VO对象
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(localDateTimes,","))
                .turnoverList(StringUtils.join(trunoverList,","))
                .build();
    }

    /**
     * 用户数量统计
     * 
 * @param begin
 * @param end
     * @return 
     * @author heiheiheng
     * @create 2025/8/13
     **/
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<Integer> userList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        dateList.forEach(data ->{
            Map map = new HashMap();
            map.put("begin", LocalDateTime.of(data, LocalTime.MIN));
            map.put("end", LocalDateTime.of(data, LocalTime.MAX));
            Integer newUserCount = userMapper.countByMap(map);
            userList.add(newUserCount);

            map.put("begin",null);
            Integer userCount = userMapper.countByMap(map);
            totalUserList.add(userCount);
        });
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(userList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<Integer> ordersList = new ArrayList<>();
        List<Integer> usefulOrdersList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer totalUsefulOrderCount = 0;
        for (LocalDate data : dateList) {
            Map map = new HashMap();
            map.put("begin", LocalDateTime.of(data, LocalTime.MIN));
            map.put("end", LocalDateTime.of(data, LocalTime.MAX));
            //统计每日订单数量
            Integer ordersCount = ordersMapper.countBtMap(map);
            ordersList.add(ordersCount);
            map.put("status",Orders.COMPLETED);
            Integer usefulOrders = ordersMapper.countBtMap(map);
            usefulOrdersList.add(usefulOrders);
            //获取订单总数
            totalOrderCount += ordersCount;
            //获取有效总订单
            totalUsefulOrderCount += usefulOrders;
        }
        //计算完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = (totalUsefulOrderCount+0.0)/ totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(ordersList,","))
                .validOrderCountList(StringUtils.join(usefulOrdersList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalUsefulOrderCount)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<String> nameList = new ArrayList<>();
        List numberList = new ArrayList<>();
        Map map = new HashMap();
        map.put("status", Orders.COMPLETED);
        map.put("begin", LocalDateTime.of(begin, LocalTime.MIN));
        map.put("end", LocalDateTime.of(end, LocalTime.MAX));
        List<Map> list = ordersMapper.sumTop10(map);
        for (Map m : list) {
            String name = (String) m.get("name");
            nameList.add(name);
            Object sumNum = m.get("sumNum");
            numberList.add(sumNum);
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) throws IOException, InvalidFormatException {
        // 1.查询近30天的运营数据
        // 2024-05-23
        LocalDate now = LocalDate.now();
        // 2024-05-22
        LocalDate end = now.minusDays(1);
        // 2024-04-22
        LocalDate begin = now.minusDays(30);
        // LocalDateTime end =
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        // 2.往Excel表中写入数据
        // 根据类加载器读取项目中的模板文件, 基于模板文件创建Excel对象
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("运营数据报表模板.xlsx");
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            //营业额
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            // 30天明细数据填充
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //4-23 00:00
                beginTime = LocalDateTime.of(date, LocalTime.MIN);
                //4-23 23:59:59.999999
                endTime = LocalDateTime.of(date, LocalTime.MAX);
                businessData = workspaceService.getBusinessData(beginTime, endTime);

                sheet.getRow(7+i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7+i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7+i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(7+i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7+i).getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 3.通过输出流将Excel文件对象下载到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            workbook.write(os);

            // 4.释放资源
            os.close();
            workbook.close();
            is.close();
        } catch (IOException e) {
            log.error("文件写入失败！！！{}",e.getMessage());
        }

    }

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> localDateTimes = new ArrayList<>();
        while (begin.isBefore(end)) {
            localDateTimes.add(begin);
            begin = begin.plusDays(1);
        }
        return localDateTimes;
    }
}
